{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "id": "8UFV0ZDwRqo3",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Pytorch入门实战（8）：小样本学习实现图片分类（Few-shot Learning, Meta Learning）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qi0R7S3dRqo6",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/iioSnail/pytorch_deep_learning_examples/blob/main/08_few_shot_learning.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8XtzTk__Rqo6",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 本文内容涉及知识点"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "s5IEY7M1Rqo6",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "1. [小样本学习的基本概念](https://blog.csdn.net/zhaohongfei_358/article/details/124057980)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dazpgGKsRqo7",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 本文内容\n",
    "\n",
    "本文会使用Omniglot数据集训练一个孪生网络（相似网络），其可以用来判断两个图片的相似程度，通过该方式来实现小样本学习。\n",
    "\n",
    "本文使用Omniglot的训练集来训练神经网络，使用其验证集来构造Support Set。本文会从验证集的每个类别中拿出5个样本作为Support Set，一共挑选10个类别，即为10-way 5-shot的小样本学习。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "C8xgOfYCRqo7",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 环境配置"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "N3dgc39NRqo7",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "本文所使用到的环境如下:\n",
    "\n",
    "```\n",
    "python==3.8.5\n",
    "torch==1.10.2\n",
    "torchvision==0.11.3\n",
    "numpy==1.22.3\n",
    "matplotlib==3.2.2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "X3-dyn6XRqo8",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "导入本文需要使用到的包："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "EW70lEcQRqo8",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "import torch\n",
    "import torchvision\n",
    "from torch import nn\n",
    "from torchvision import transforms\n",
    "\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "BtGR9v38Rqo9",
    "outputId": "22ec7ede-4fd5-4189-c570-9f939932645b",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Device: cuda\n"
     ]
    }
   ],
   "source": [
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "print(\"Device:\", device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GP85g-E_Rqo9",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 加载数据集"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gxfAzwOpRqo-",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们这里使用Pytorch提供的`torchvision.datasets.Omniglot`的方法来加载数据集。\n",
    "\n",
    "> 如果你用pytorch下载失败，可以使用[百度网盘链接](https://pan.baidu.com/s/1I3UGUjqEgGKVfxgZEt5H6w?pwd=v6pu)下载，然后解压到当前文件夹下，将`download`参数改为`False`即可"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 90,
     "referenced_widgets": [
      "b6b2448bddef4a4bbb81a5c840ce55e3",
      "6a70570b29f646e98fa0b46f90598789",
      "ca2ca4a075434724b9c7acf4dd2c6594",
      "669f3424b7bf4ff5826dc22656034968",
      "137871bf75e94ebd800f03925a8f0bd6",
      "3dff9f5e976b46708151c488351c1f94",
      "df1635a7d8d345a485e5be157c9b7941",
      "cf34a757e5954b0eaea406ffd4a2edb2",
      "1946f6e0fb144b31b41df744f7c2eefb",
      "a69905a4e5424682b64022e716042800",
      "3689fb39a2fe4c7ebef9656ae7b54f5c",
      "64f97da934bb4765bc77eb5b6e45e447",
      "d14781bec20f41f0baeae04f5808221f",
      "e15ffd780be2410cac528b1c1dcef6e7",
      "a3faf9beb6024fce8ca35e40149e1aca",
      "09aaa058ade64839b6b7164288581257",
      "8491bceba2434248aa96dd9163bada0e",
      "e972b2b7008a42ac97b08f1251ddb259",
      "6f2c804fca9645de9f53b4183308d9f9",
      "a52f65ea28b048b0b756ec631a70f064",
      "600bb6c52be94b0bb88e7eead258e26a",
      "80b3ee0e64a84710b1afcaaf4ff25126"
     ]
    },
    "id": "Pu01UDiuRqo-",
    "outputId": "91071d59-3d65-4315-a0d1-cb92bca087d7",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading https://raw.githubusercontent.com/brendenlake/omniglot/master/python/images_background.zip to ./dataset/omniglot-py/images_background.zip\n"
     ]
    },
    {
     "data": {
      "application/json": {
       "ascii": false,
       "bar_format": null,
       "colour": null,
       "elapsed": 0.022606849670410156,
       "initial": 0,
       "n": 0,
       "ncols": null,
       "nrows": null,
       "postfix": null,
       "prefix": "",
       "rate": null,
       "total": 9464212,
       "unit": "it",
       "unit_divisor": 1000,
       "unit_scale": false
      },
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b6b2448bddef4a4bbb81a5c840ce55e3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/9464212 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./dataset/omniglot-py/images_background.zip to ./dataset/omniglot-py\n",
      "Downloading https://raw.githubusercontent.com/brendenlake/omniglot/master/python/images_evaluation.zip to ./dataset/omniglot-py/images_evaluation.zip\n"
     ]
    },
    {
     "data": {
      "application/json": {
       "ascii": false,
       "bar_format": null,
       "colour": null,
       "elapsed": 0.04923248291015625,
       "initial": 0,
       "n": 0,
       "ncols": null,
       "nrows": null,
       "postfix": null,
       "prefix": "",
       "rate": null,
       "total": 6462886,
       "unit": "it",
       "unit_divisor": 1000,
       "unit_scale": false
      },
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "64f97da934bb4765bc77eb5b6e45e447",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "  0%|          | 0/6462886 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./dataset/omniglot-py/images_evaluation.zip to ./dataset/omniglot-py\n"
     ]
    }
   ],
   "source": [
    "train_dataset = torchvision.datasets.Omniglot('./dataset', background=True, transform=transforms.ToTensor(), download=True)\n",
    "validation_dataset = torchvision.datasets.Omniglot('./dataset', background=False, transform=transforms.ToTensor(), download=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EwHmKNdSRqo-",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "成功加载完数据集后我们来简单看一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "2SfYCe54Rqo-",
    "outputId": "2744c55b-9ba8-4872-e22d-c7c67c90c596",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image size: torch.Size([1, 105, 105])\n",
      "target: 0\n"
     ]
    }
   ],
   "source": [
    "image, target = train_dataset.__getitem__(0)\n",
    "print(\"image size:\", image.size())\n",
    "print(\"target:\", target)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aSLKYgeeRqo-",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Omniglot数据集都是一张一张的灰度图，和MNIST手写数据集差不多。这个target就是用数字表示的类别，我也不知道对应成实际类别是什么，也不需要知道。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oMwAqw-2Rqo_",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们来简单绘制一张看一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 286
    },
    "id": "bxpaBVhBRqo_",
    "outputId": "772a8b55-93d3-4803-92e3-626884a66e20",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x7fe2487f21d0>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAQEAAAD7CAYAAABqkiE2AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAYjUlEQVR4nO3de3RU9b338feXXAiESwKJiIRLaEBFvJSkBUsfS1VAWpZXqlg90lMvRT1LPM+xap+2q+hiqW2PeqzrtKvUeqCtNaKisHiqp15wPdZWTuPRcpF7EMIlEIEYCBIS5vv8kYGTajCTzGXvsD+vtWYls2fPzCc78Mlv/2bPHnN3RCS6egQdQESCpR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0yX6PCUMJhJqZ9QGeB+5094a2t3lr1Qb2GquZTQf2uPs7QWVIUDYwDviFu3+e1veJ/N3QPwTbspDWU+aXAqcB+Xx6CB5KyW67MJRAaE9OamY5tBbAU+6+OL74RCdZDcJE4FIz+wCopHWX4DFaP+/h2FmjwrA9twPb3X1F/PpztJZCmLblxcAWd69z92ZgMa3bN2zb8piUnew3DCXwV2BUfBY2l9bJmKUBZ8LMDPg1sNbdH2lz04lOsppx7v49dy9x9xG0brfX3f06YDkwI75aoBkB3L0WqDGz0+OLLgLeJ0TbktbdgAlm1jv+uz+WMVTbso3Unew3qImYT0x6fA3YAGwGvh90nnimL9M6xFoJvBe/fI3Wfe7XgI3Aq8CAoLPG804ClsW/Hwn8F60nfH0W6BmCfOcBVfHt+SJQGLZtCdwHrANWA78FeoZhWwJP0zpP0UzrqOrGE207WieG/z3+f2kVra92fObj67BhkYgLw+6AiARIJSAScSoBkYhTCYhEnEpAJOJUAiIRpxIQibj/D8QGZUwkniFcAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.imshow(image.squeeze(), cmap='gray')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1QKipHDWRqo_",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 数据处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fsEecM8KRqo_",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "在孪生网络中，我们一次给到模型的是一对儿图片，然后让模型来区分这对儿图片是否是相同的类别。我们本章就需要来定义这么一个函数，来生成一批样本对儿，其中一半图片对儿是相同类别，另一半图片对儿是不同类别。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "fUP09dgxRqo_",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们首先获取一下训练集中的所有target和所有labels："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "AIcig3GDRqo_",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "all_targets = np.array([train_dataset.__getitem__(i)[1] for i in range(len(train_dataset))])\n",
    "all_labels = np.array(list(set(all_targets)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "MJuDqiJ7Rqo_",
    "outputId": "f9ace71e-332b-45fe-c05a-eb5c19fb33a1",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "all_targets: [  0   0   0 ... 963 963 963]\n",
      "all_labels: [  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17\n",
      "  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35\n",
      "  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53\n",
      "  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71\n",
      "  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89\n",
      "  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107\n",
      " 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125\n",
      " 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143\n",
      " 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161\n",
      " 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179\n",
      " 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197\n",
      " 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215\n",
      " 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233\n",
      " 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251\n",
      " 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269\n",
      " 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287\n",
      " 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305\n",
      " 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323\n",
      " 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341\n",
      " 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359\n",
      " 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377\n",
      " 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395\n",
      " 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413\n",
      " 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431\n",
      " 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449\n",
      " 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467\n",
      " 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485\n",
      " 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503\n",
      " 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521\n",
      " 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539\n",
      " 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557\n",
      " 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575\n",
      " 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593\n",
      " 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611\n",
      " 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629\n",
      " 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647\n",
      " 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665\n",
      " 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683\n",
      " 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701\n",
      " 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719\n",
      " 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737\n",
      " 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755\n",
      " 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773\n",
      " 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791\n",
      " 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809\n",
      " 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827\n",
      " 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845\n",
      " 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863\n",
      " 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881\n",
      " 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899\n",
      " 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917\n",
      " 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935\n",
      " 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953\n",
      " 954 955 956 957 958 959 960 961 962 963]\n"
     ]
    }
   ],
   "source": [
    "print(\"all_targets:\", all_targets)\n",
    "print(\"all_labels:\", all_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Nk7g9R70RqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "准备好了这两个基础数据，我们就可以来构造我们的Sample函数了。其作用就是返回一个batch的图片对儿，其中一半是相同的类别，称为**正样本**，另一半是不同的类别，称为**负样本**。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "IJGXj22ERqpA",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "def sample_batch(batch_size):\n",
    "    \"\"\"\n",
    "    从train_dataset中sample一些数据对。一半正样本，一半负样本\n",
    "    \"\"\"\n",
    "\n",
    "    # 选取二分之一个batch的labels作为正样本，这样就完成了正样本的构造。\n",
    "    positive_labels = np.random.choice(all_labels, batch_size // 2)\n",
    "    # 针对这些labels，每个选取两张相同类别的图片\n",
    "    batch = []\n",
    "    for label in positive_labels:\n",
    "        labels_indexes = np.argwhere(all_targets == label)\n",
    "        pair = np.random.choice(labels_indexes.flatten(), 2)\n",
    "        batch.append((pair[0], pair[1], 1)) # 图片类别相同，所以target为1\n",
    "\n",
    "    # 选取负样本，这次选取一个batch的labels，然后每个labels个选取一张图片。这样就完成了负样本的构造。\n",
    "    negative_labels = np.random.choice(all_labels, batch_size)\n",
    "    for sample1, sample2 in negative_labels.reshape(-1, 2):\n",
    "        sample1 = np.random.choice(np.argwhere(all_targets == sample1).flatten(), 1)\n",
    "        sample2 = np.random.choice(np.argwhere(all_targets == sample2).flatten(), 1)\n",
    "        batch.append((sample1.item(), sample2.item(), 0)) # 图片类别不相同，所以target为0\n",
    "\n",
    "    \"\"\"\n",
    "    完成上面的动作后，最终得到的batch如下：\n",
    "        (734, 736, 1),\n",
    "        (127, 132, 1),\n",
    "        ...\n",
    "        (859, 173, 0),\n",
    "        ...\n",
    "    其中前两个表示样本对对应在dataset中的index，1表示前两个样本是相同类别。0表示这两个样本为不同类别。\n",
    "    接下来需要对其进行shuffle处理，然后从dataset中获取到对应数据，最终组成batch.\n",
    "    \"\"\"\n",
    "    random.shuffle(batch)\n",
    "\n",
    "    sample1_list = []\n",
    "    sample2_list = []\n",
    "    target_list = []\n",
    "    for sample1, sample2, target in batch:\n",
    "        sample1_list.append(train_dataset.__getitem__(sample1)[0])\n",
    "        sample2_list.append(train_dataset.__getitem__(sample2)[0])\n",
    "        target_list.append(target)\n",
    "    sample1 = torch.stack(sample1_list)\n",
    "    sample2 = torch.stack(sample2_list)\n",
    "    targets = torch.LongTensor(target_list)\n",
    "    return sample1, sample2, targets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8vaX3nHORqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "完成sample函数后，我们来简单试一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "Tc0KuVsVRqpA",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "sample1, sample2, targets = sample_batch(16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "cfqbhQkORqpA",
    "outputId": "485a5403-8ecb-401e-ffa5-ef22849df8c6",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample1: torch.Size([16, 1, 105, 105])\n",
      "sample2: torch.Size([16, 1, 105, 105])\n",
      "targets: tensor([1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1])\n"
     ]
    }
   ],
   "source": [
    "print(\"sample1:\", sample1.size())\n",
    "print(\"sample2:\", sample1.size())\n",
    "print(\"targets:\", targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aZKsK9tbRqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "其中`sample1[0]`和`smaple2[0]` 是一对儿，`targets[0]`是它们的标签，表示它们是否是相同类别。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jpRvfs6lRqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "准备好数据后，我们接下来开始构建模型："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ACcdz8G0RqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 模型构建"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4azk7aUXRqpA",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们需要构建的模型也很简单，模型的功能就是输入两张图片，输出这两张图片是否为同一个类别。由于是二分类问题，所以我们最后的值通过Sigmoid处理一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "ZjC0TZCJRqpA",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "class SimilarityModel(nn.Module):\n",
    "\n",
    "    def __init__(self):\n",
    "        super(SimilarityModel, self).__init__()\n",
    "\n",
    "        # 定义一个卷积层，用于特征提取。\n",
    "        self.conv = nn.Sequential(\n",
    "            nn.Conv2d(1, 4, kernel_size=3),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=2, stride=2),\n",
    "            nn.Conv2d(4, 16, kernel_size=3),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=2, stride=2),\n",
    "            nn.Conv2d(16, 32, kernel_size=3),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=2, stride=2),\n",
    "            nn.Conv2d(32, 32, kernel_size=3),\n",
    "            nn.ReLU(),\n",
    "        )\n",
    "\n",
    "        # 定义一个线性层，用来判断两张图片是否为同一类别\n",
    "        self.sim = nn.Sequential(\n",
    "            nn.Flatten(),\n",
    "            nn.Linear(2592, 256),\n",
    "            nn.ReLU(),\n",
    "            nn.Linear(256, 1),\n",
    "            nn.Sigmoid()\n",
    "        )\n",
    "\n",
    "    def forward(self, sample1, sample2):\n",
    "        # 使用卷积层提取sample1的特征\n",
    "        sample1_features = self.conv(sample1)\n",
    "        # 使用卷积层提取sample2的特征\n",
    "        sample2_features = self.conv(sample2)\n",
    "        # 将 |sample1-sample2| 的结果送给线性层，判断它们的相似度。\n",
    "        return self.sim(torch.abs(sample1_features - sample2_features))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "qklx-hFMRqpB",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "model = SimilarityModel()\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "AkeTEHI7RqpB",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "模型定义完后，我们来简单的尝试一下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "4wxjJr4KRqpB",
    "outputId": "d2bfdfd3-dd87-40b3-fda7-9d8d10c08759",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.5004],\n",
       "        [0.5005],\n",
       "        [0.5003],\n",
       "        [0.5005],\n",
       "        [0.5000],\n",
       "        [0.5004],\n",
       "        [0.5005],\n",
       "        [0.5004],\n",
       "        [0.5000],\n",
       "        [0.5004],\n",
       "        [0.5006],\n",
       "        [0.5001],\n",
       "        [0.5002],\n",
       "        [0.5003],\n",
       "        [0.5000],\n",
       "        [0.5002]], device='cuda:0', grad_fn=<SigmoidBackward0>)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model(sample1.to(device), sample2.to(device))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "utTa1bd6RqpB",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "可以看到，由于模型还未训练，所以输出的值都在50%左右。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lif2PeqDRqpB",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 训练模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0bNjn2iDRqpB",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "接下来开始训练模型，和普通的二分类问题差别不算很大。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "tReg9qQERqpB",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "model = model.train()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "QPnOUbrORqpB",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "criteria = nn.BCELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "vfNTvFWqRqpB",
    "outputId": "51743b29-44a5-4470-c5eb-bceaf6cbfee0",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "episode 0, loss 0.6931208372116089\n",
      "episode 50, loss 0.6730687618255615\n",
      "episode 100, loss 0.6514454483985901\n",
      "episode 150, loss 0.6112750768661499\n",
      "episode 200, loss 0.5643270015716553\n",
      "episode 250, loss 0.4998775124549866\n",
      "episode 300, loss 0.562949001789093\n",
      "episode 350, loss 0.49458998441696167\n",
      "episode 400, loss 0.4829554855823517\n",
      "episode 450, loss 0.50950688123703\n",
      "episode 500, loss 0.44546687602996826\n",
      "episode 550, loss 0.4880187511444092\n",
      "episode 600, loss 0.43081381916999817\n",
      "episode 650, loss 0.42522192001342773\n",
      "episode 700, loss 0.43799975514411926\n",
      "episode 750, loss 0.4290987253189087\n",
      "episode 800, loss 0.400988906621933\n",
      "episode 850, loss 0.43764418363571167\n",
      "episode 900, loss 0.3570705056190491\n",
      "episode 950, loss 0.40238815546035767\n",
      "episode 1000, loss 0.42024746537208557\n",
      "episode 1050, loss 0.39611750841140747\n",
      "episode 1100, loss 0.3548458516597748\n",
      "episode 1150, loss 0.31902915239334106\n",
      "episode 1200, loss 0.30719077587127686\n",
      "episode 1250, loss 0.3704574704170227\n",
      "episode 1300, loss 0.39360809326171875\n",
      "episode 1350, loss 0.31774747371673584\n",
      "episode 1400, loss 0.2935783267021179\n",
      "episode 1450, loss 0.32135486602783203\n",
      "episode 1500, loss 0.2940015196800232\n",
      "episode 1550, loss 0.31895336508750916\n",
      "episode 1600, loss 0.3236328959465027\n",
      "episode 1650, loss 0.278342068195343\n",
      "episode 1700, loss 0.29538559913635254\n",
      "episode 1750, loss 0.34522032737731934\n",
      "episode 1800, loss 0.30923986434936523\n",
      "episode 1850, loss 0.26237526535987854\n",
      "episode 1900, loss 0.2846532464027405\n",
      "episode 1950, loss 0.2567117214202881\n",
      "episode 2000, loss 0.25510355830192566\n",
      "episode 2050, loss 0.2495623379945755\n",
      "episode 2100, loss 0.3096069097518921\n",
      "episode 2150, loss 0.26960819959640503\n",
      "episode 2200, loss 0.2586340010166168\n",
      "episode 2250, loss 0.27671104669570923\n",
      "episode 2300, loss 0.2596566081047058\n",
      "episode 2350, loss 0.2601384222507477\n",
      "episode 2400, loss 0.2463243156671524\n",
      "episode 2450, loss 0.27323123812675476\n",
      "episode 2500, loss 0.22680455446243286\n",
      "episode 2550, loss 0.24704509973526\n",
      "episode 2600, loss 0.22310321033000946\n",
      "episode 2650, loss 0.24409082531929016\n",
      "episode 2700, loss 0.3104301393032074\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "ignored",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mKeyboardInterrupt\u001B[0m                         Traceback (most recent call last)",
      "\u001B[0;32m<ipython-input-16-995257fcab99>\u001B[0m in \u001B[0;36m<module>\u001B[0;34m\u001B[0m\n\u001B[1;32m      9\u001B[0m \u001B[0;32mfor\u001B[0m \u001B[0mepisode\u001B[0m \u001B[0;32min\u001B[0m \u001B[0mrange\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0;36m100000\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     10\u001B[0m     \u001B[0;31m# 使用sample_batch函数sample出一组数据，包含一半正样本，一半负样本\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m---> 11\u001B[0;31m     \u001B[0msample1\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0msample2\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mtargets\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0msample_batch\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mbatch_size\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m     12\u001B[0m     \u001B[0;31m# 将数据送入模型，判断是否为同一类别\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     13\u001B[0m     \u001B[0moutputs\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mmodel\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0msample1\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mto\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mdevice\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0msample2\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mto\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mdevice\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m<ipython-input-8-568b86ab946d>\u001B[0m in \u001B[0;36msample_batch\u001B[0;34m(batch_size)\u001B[0m\n\u001B[1;32m     37\u001B[0m     \u001B[0;32mfor\u001B[0m \u001B[0msample1\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0msample2\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mtarget\u001B[0m \u001B[0;32min\u001B[0m \u001B[0mbatch\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     38\u001B[0m         \u001B[0msample1_list\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mappend\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mtrain_dataset\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m__getitem__\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0msample1\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m[\u001B[0m\u001B[0;36m0\u001B[0m\u001B[0;34m]\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m---> 39\u001B[0;31m         \u001B[0msample2_list\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mappend\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mtrain_dataset\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m__getitem__\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0msample2\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m[\u001B[0m\u001B[0;36m0\u001B[0m\u001B[0;34m]\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m     40\u001B[0m         \u001B[0mtarget_list\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mappend\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mtarget\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     41\u001B[0m     \u001B[0msample1\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mtorch\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mstack\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0msample1_list\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/torchvision/datasets/omniglot.py\u001B[0m in \u001B[0;36m__getitem__\u001B[0;34m(self, index)\u001B[0m\n\u001B[1;32m     73\u001B[0m         \u001B[0mimage_name\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mcharacter_class\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m_flat_character_images\u001B[0m\u001B[0;34m[\u001B[0m\u001B[0mindex\u001B[0m\u001B[0;34m]\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     74\u001B[0m         \u001B[0mimage_path\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mjoin\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mtarget_folder\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m_characters\u001B[0m\u001B[0;34m[\u001B[0m\u001B[0mcharacter_class\u001B[0m\u001B[0;34m]\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mimage_name\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m---> 75\u001B[0;31m         \u001B[0mimage\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mImage\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mopen\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mimage_path\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mmode\u001B[0m\u001B[0;34m=\u001B[0m\u001B[0;34m\"r\"\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mconvert\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0;34m\"L\"\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m     76\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m     77\u001B[0m         \u001B[0;32mif\u001B[0m \u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mtransform\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/Image.py\u001B[0m in \u001B[0;36mopen\u001B[0;34m(fp, mode)\u001B[0m\n\u001B[1;32m   2879\u001B[0m         \u001B[0;32mreturn\u001B[0m \u001B[0;32mNone\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m   2880\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m-> 2881\u001B[0;31m     \u001B[0mim\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0m_open_core\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mfp\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mfilename\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mprefix\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m   2882\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m   2883\u001B[0m     \u001B[0;32mif\u001B[0m \u001B[0mim\u001B[0m \u001B[0;32mis\u001B[0m \u001B[0;32mNone\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/Image.py\u001B[0m in \u001B[0;36m_open_core\u001B[0;34m(fp, filename, prefix)\u001B[0m\n\u001B[1;32m   2865\u001B[0m                 \u001B[0;32melif\u001B[0m \u001B[0mresult\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m   2866\u001B[0m                     \u001B[0mfp\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mseek\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0;36m0\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m-> 2867\u001B[0;31m                     \u001B[0mim\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mfactory\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mfp\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mfilename\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m   2868\u001B[0m                     \u001B[0m_decompression_bomb_check\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mim\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0msize\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m   2869\u001B[0m                     \u001B[0;32mreturn\u001B[0m \u001B[0mim\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/ImageFile.py\u001B[0m in \u001B[0;36m__init__\u001B[0;34m(self, fp, filename)\u001B[0m\n\u001B[1;32m    105\u001B[0m         \u001B[0;32mtry\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    106\u001B[0m             \u001B[0;32mtry\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m--> 107\u001B[0;31m                 \u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m_open\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m    108\u001B[0m             except (\n\u001B[1;32m    109\u001B[0m                 \u001B[0mIndexError\u001B[0m\u001B[0;34m,\u001B[0m  \u001B[0;31m# end of data\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/PngImagePlugin.py\u001B[0m in \u001B[0;36m_open\u001B[0;34m(self)\u001B[0m\n\u001B[1;32m    659\u001B[0m                 \u001B[0ms\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mImageFile\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0m_safe_read\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mfp\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mlength\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    660\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m--> 661\u001B[0;31m             \u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mpng\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mcrc\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mcid\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0ms\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m    662\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    663\u001B[0m         \u001B[0;31m#\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/PngImagePlugin.py\u001B[0m in \u001B[0;36mcrc\u001B[0;34m(self, cid, data)\u001B[0m\n\u001B[1;32m    165\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    166\u001B[0m         \u001B[0;32mtry\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m--> 167\u001B[0;31m             \u001B[0mcrc1\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0m_crc32\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mdata\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0m_crc32\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mcid\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m    168\u001B[0m             \u001B[0mcrc2\u001B[0m \u001B[0;34m=\u001B[0m \u001B[0mi32\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mself\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mfp\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mread\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0;36m4\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    169\u001B[0m             \u001B[0;32mif\u001B[0m \u001B[0mcrc1\u001B[0m \u001B[0;34m!=\u001B[0m \u001B[0mcrc2\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;32m/usr/local/lib/python3.7/dist-packages/PIL/PngImagePlugin.py\u001B[0m in \u001B[0;36m_crc32\u001B[0;34m(data, seed)\u001B[0m\n\u001B[1;32m    103\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    104\u001B[0m \u001B[0;32mdef\u001B[0m \u001B[0m_crc32\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mdata\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mseed\u001B[0m\u001B[0;34m=\u001B[0m\u001B[0;36m0\u001B[0m\u001B[0;34m)\u001B[0m\u001B[0;34m:\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0;32m--> 105\u001B[0;31m     \u001B[0;32mreturn\u001B[0m \u001B[0mzlib\u001B[0m\u001B[0;34m.\u001B[0m\u001B[0mcrc32\u001B[0m\u001B[0;34m(\u001B[0m\u001B[0mdata\u001B[0m\u001B[0;34m,\u001B[0m \u001B[0mseed\u001B[0m\u001B[0;34m)\u001B[0m \u001B[0;34m&\u001B[0m \u001B[0;36m0xFFFFFFFF\u001B[0m\u001B[0;34m\u001B[0m\u001B[0;34m\u001B[0m\u001B[0m\n\u001B[0m\u001B[1;32m    106\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n\u001B[1;32m    107\u001B[0m \u001B[0;34m\u001B[0m\u001B[0m\n",
      "\u001B[0;31mKeyboardInterrupt\u001B[0m: "
     ]
    }
   ],
   "source": [
    "batch_size = 512\n",
    "# 如果500次迭代loss都没有下降，那么就停止训练\n",
    "early_stop = 1500\n",
    "# 记录最小的一次loss值\n",
    "min_loss = 100.\n",
    "# 记录下上一次最小的loss是哪一次\n",
    "last_episode = 0\n",
    "# 无线更新参数，直到loss不再下降为止\n",
    "for episode in range(100000):\n",
    "    # 使用sample_batch函数sample出一组数据，包含一半正样本，一半负样本\n",
    "    sample1, sample2, targets = sample_batch(batch_size)\n",
    "    # 将数据送入模型，判断是否为同一类别\n",
    "    outputs = model(sample1.to(device), sample2.to(device))\n",
    "    # 将模型的结果丢给BCELoss计算损失\n",
    "    loss = criteria(outputs.flatten(), targets.to(device).float())\n",
    "    loss.backward()\n",
    "    # 更新模型参数\n",
    "    optimizer.step()\n",
    "    optimizer.zero_grad()\n",
    "\n",
    "    # 如果本次损失比之前的小，那么记录一下\n",
    "    if loss < min_loss:\n",
    "        min_loss = loss.item()\n",
    "        last_episode = episode\n",
    "        torch.save(model, 'best_model.pt')\n",
    "\n",
    "    # 如果连续{early_stop}次loss都没有减小，那么就停止训练\n",
    "    if episode - last_episode > early_stop:\n",
    "        break\n",
    "\n",
    "    # 每50个episode打印一下日志\n",
    "    if episode % 50 ==  0:\n",
    "        print(f\"episode {episode}, loss {loss}\")\n",
    "\n",
    "print(\"Finish Training.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CQeqmNBhRqpB",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 模型验证"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ntPapqjqRqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "验证前先加载一下之前最好的模型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "id": "9fop1AoVRqpC",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "model = torch.load('best_model.pt')\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "82d2duxARqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "接下来我们来验证下我们模型的表现。我们使用上面构造好的validation_dataset。在validation_dataset中，全都是模型之间没有见过的类别，可不是没有见过的图片哦，连这个类别它都没有见过。不信你可以到`dataset/images_evaluation`这个目录下表看看那。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "07H3sil8RqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们先来看下验证集中的类别情况："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "id": "q16ZOaRRRqpC",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "all_targets = np.array([validation_dataset.__getitem__(i)[1] for i in range(len(validation_dataset))])\n",
    "all_labels = np.array(list(set(all_targets)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "65sEiD9iRqpC",
    "outputId": "f6b78d82-f1b8-47fc-d24e-6e40251b46e9",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample size: 13180\n",
      "all_targets: [  0   0   0 ... 658 658 658]\n",
      "all_labels: [  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17\n",
      "  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35\n",
      "  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53\n",
      "  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71\n",
      "  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89\n",
      "  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107\n",
      " 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125\n",
      " 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143\n",
      " 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161\n",
      " 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179\n",
      " 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197\n",
      " 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215\n",
      " 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233\n",
      " 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251\n",
      " 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269\n",
      " 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287\n",
      " 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305\n",
      " 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323\n",
      " 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341\n",
      " 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359\n",
      " 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377\n",
      " 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395\n",
      " 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413\n",
      " 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431\n",
      " 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449\n",
      " 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467\n",
      " 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485\n",
      " 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503\n",
      " 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521\n",
      " 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539\n",
      " 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557\n",
      " 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575\n",
      " 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593\n",
      " 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611\n",
      " 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629\n",
      " 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647\n",
      " 648 649 650 651 652 653 654 655 656 657 658]\n"
     ]
    }
   ],
   "source": [
    "print(\"sample size:\", len(all_targets))\n",
    "print(\"all_targets:\", all_targets)\n",
    "print(\"all_labels:\", all_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "g47eY7OyRqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "可以看到，在验证集中我们一共有13180个数据，有658个类别，每个类别有20个样本。我们为每个类别选取5个样本作为support set供模型参考，剩下的15个作为验证集来验证模型的表现。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dSPKvACgRqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "如果对这658个类别全部都做预测的话，相当于我们的任务是一个658-way 5-shot的任务。这样不仅预测过程会非常慢，并且准确率也会非常低，所以上面的简单模型就应付不了了。为了简单期间，我们这里裁剪一下，就使用10个类别来验证我们的模型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "2Mrx_dU8RqpC",
    "outputId": "f9969095-8561-4f15-817c-0a9ca57dc9af",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sample size: 200\n",
      "all_targets: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
      " 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3\n",
      " 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5\n",
      " 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7\n",
      " 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9\n",
      " 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9]\n",
      "all_labels: [0 1 2 3 4 5 6 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "all_targets = all_targets[all_targets < 10]\n",
    "all_labels = all_labels[:10]\n",
    "print(\"sample size:\", len(all_targets))\n",
    "print(\"all_targets:\", all_targets)\n",
    "print(\"all_labels:\", all_labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "id": "DyFWA0-wRqpC",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "support_set = []\n",
    "validation_set = []\n",
    "# 遍历所有的标签，每个标签选取前5个作为support set，后面的作为验证数据\n",
    "for label in all_labels:\n",
    "    label_indexes = np.argwhere(all_targets == label)\n",
    "    support_set.append((label_indexes[:5].flatten().tolist()))\n",
    "    validation_set += label_indexes[5:].flatten().tolist()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "FfvpdvGGRqpC",
    "outputId": "55c5604c-0b58-441e-b50d-4992e64400da",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "support set: [[0, 1, 2, 3, 4], [20, 21, 22, 23, 24], [40, 41, 42, 43, 44], [60, 61, 62, 63, 64], [80, 81, 82, 83, 84]]\n",
      "validation set: [5, 6, 7, 8, 9]\n",
      "validation size: 150\n"
     ]
    }
   ],
   "source": [
    "print(\"support set:\", support_set[:5])\n",
    "print(\"validation set:\", validation_set[:5])\n",
    "print(\"validation size:\", len(validation_set))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "p5OdeIN0RqpC",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们接下来需要定义一个预测函数，其给定一个图片，输出该图片的target。该函数的思路为：让该图片与support set里的所有类别都比较一下，看看与谁的相似度最高，那么该图片就是什么类别。由于一个类别有5张图片，我们可以通过取平均的方式来得到该图片为该类别的可能性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "id": "IsIGiUL9RqpC",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "def predict(image):\n",
    "    sim_list = [] # 存储image与每个类别的相似度\n",
    "    # 一个类别一个类别的遍历，indexes存储的就是当前类别的5张图片的index\n",
    "    for indexes in support_set:\n",
    "        # 去validation_dataset中找出index对应的图片tensor\n",
    "        tensor_list = []\n",
    "        for i in indexes:\n",
    "            tensor_list.append(validation_dataset[i][0])\n",
    "        support_tensor = torch.stack(tensor_list)\n",
    "        # 拿到该类别的5个图片后，就可以送给模型求image与它们的相似程度了，最后求个平均\n",
    "        sim = model(image.repeat(5, 1, 1, 1).to(device), support_tensor.to(device)).mean()\n",
    "        sim_list.append(sim)\n",
    "\n",
    "    # 找出其中相似程度最高的那个，它就是预测结果\n",
    "    result_index = torch.stack(sim_list).argmax().item()\n",
    "    return all_labels[result_index]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Up_6__fgRqpD",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "我们来试下predict函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "mFZ4S3xKRqpD",
    "outputId": "bbb1c1dd-7a71-4818-d410-00bfaec12810",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predict(validation_dataset.__getitem__(validation_set[0])[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9zd8O5XORqpD",
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "最后我们一个个的对验证集的数据进行验证，计算正确率。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "PiCkEubNRqpD",
    "outputId": "7f7ad66e-6e9f-47fc-cb70-c4df0c3d44f9",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 150/150 [00:06<00:00, 21.66it/s, accuracy=0.700]\n"
     ]
    }
   ],
   "source": [
    "total = 0\n",
    "total_correct = 0\n",
    "\n",
    "# 由于验证集太大，为了更快的看到效果，我们验证前，将validation_set打乱一下再验证\n",
    "random.shuffle(validation_set)\n",
    "progress = tqdm(validation_set)\n",
    "\n",
    "for i in progress:\n",
    "    image, label = validation_dataset.__getitem__(i)\n",
    "    predict_label = predict(image)\n",
    "\n",
    "    total += 1\n",
    "    if predict_label == label:\n",
    "        total_correct += 1\n",
    "\n",
    "    progress.set_postfix({\n",
    "            \"accuracy\": str(\"%.3f\" % (total_correct / total))\n",
    "        })"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "j3Bd3BSLRqpD",
    "outputId": "3d85bfd0-8c9c-4e01-facd-149c6ea5ca4b",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.7\n"
     ]
    }
   ],
   "source": [
    "print(\"Accuracy:\", total_correct / total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "最终，在这150个验证数据中，我们取得了70%的正确率，不算太高，但至少能说明模型是有效果的。\n",
    "\n",
    "> 由于模型结构是我拍脑袋随便想的，而且比较小，所以如果用全部的658个类别做预测的话，效果会比较差，正确率大概只有15%左右，感兴趣的朋友可以尝试一下，并且优化模型。"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "machine_shape": "hm",
   "provenance": []
  },
  "gpuClass": "standard",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "09aaa058ade64839b6b7164288581257": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "137871bf75e94ebd800f03925a8f0bd6": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "1946f6e0fb144b31b41df744f7c2eefb": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "ProgressStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "ProgressStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "bar_color": null,
      "description_width": ""
     }
    },
    "3689fb39a2fe4c7ebef9656ae7b54f5c": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "background": null,
      "description_width": "",
      "font_size": null,
      "text_color": null
     }
    },
    "3dff9f5e976b46708151c488351c1f94": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "600bb6c52be94b0bb88e7eead258e26a": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "64f97da934bb4765bc77eb5b6e45e447": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HBoxModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HBoxModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HBoxView",
      "box_style": "",
      "children": [
       "IPY_MODEL_d14781bec20f41f0baeae04f5808221f",
       "IPY_MODEL_e15ffd780be2410cac528b1c1dcef6e7",
       "IPY_MODEL_a3faf9beb6024fce8ca35e40149e1aca"
      ],
      "layout": "IPY_MODEL_09aaa058ade64839b6b7164288581257",
      "tabbable": null,
      "tooltip": null
     }
    },
    "669f3424b7bf4ff5826dc22656034968": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HTMLView",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_a69905a4e5424682b64022e716042800",
      "placeholder": "​",
      "style": "IPY_MODEL_3689fb39a2fe4c7ebef9656ae7b54f5c",
      "tabbable": null,
      "tooltip": null,
      "value": " 9464212/9464212 [00:00&lt;00:00, 69446867.15it/s]"
     }
    },
    "6a70570b29f646e98fa0b46f90598789": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HTMLView",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_3dff9f5e976b46708151c488351c1f94",
      "placeholder": "​",
      "style": "IPY_MODEL_df1635a7d8d345a485e5be157c9b7941",
      "tabbable": null,
      "tooltip": null,
      "value": "100%"
     }
    },
    "6f2c804fca9645de9f53b4183308d9f9": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "80b3ee0e64a84710b1afcaaf4ff25126": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "background": null,
      "description_width": "",
      "font_size": null,
      "text_color": null
     }
    },
    "8491bceba2434248aa96dd9163bada0e": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "a3faf9beb6024fce8ca35e40149e1aca": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HTMLView",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_600bb6c52be94b0bb88e7eead258e26a",
      "placeholder": "​",
      "style": "IPY_MODEL_80b3ee0e64a84710b1afcaaf4ff25126",
      "tabbable": null,
      "tooltip": null,
      "value": " 6462886/6462886 [00:00&lt;00:00, 9099915.81it/s]"
     }
    },
    "a52f65ea28b048b0b756ec631a70f064": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "ProgressStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "ProgressStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "bar_color": null,
      "description_width": ""
     }
    },
    "a69905a4e5424682b64022e716042800": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "b6b2448bddef4a4bbb81a5c840ce55e3": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HBoxModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HBoxModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HBoxView",
      "box_style": "",
      "children": [
       "IPY_MODEL_6a70570b29f646e98fa0b46f90598789",
       "IPY_MODEL_ca2ca4a075434724b9c7acf4dd2c6594",
       "IPY_MODEL_669f3424b7bf4ff5826dc22656034968"
      ],
      "layout": "IPY_MODEL_137871bf75e94ebd800f03925a8f0bd6",
      "tabbable": null,
      "tooltip": null
     }
    },
    "ca2ca4a075434724b9c7acf4dd2c6594": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "FloatProgressModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "FloatProgressModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "ProgressView",
      "bar_style": "success",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_cf34a757e5954b0eaea406ffd4a2edb2",
      "max": 9464212,
      "min": 0,
      "orientation": "horizontal",
      "style": "IPY_MODEL_1946f6e0fb144b31b41df744f7c2eefb",
      "tabbable": null,
      "tooltip": null,
      "value": 9464212
     }
    },
    "cf34a757e5954b0eaea406ffd4a2edb2": {
     "model_module": "@jupyter-widgets/base",
     "model_module_version": "2.0.0",
     "model_name": "LayoutModel",
     "state": {
      "_model_module": "@jupyter-widgets/base",
      "_model_module_version": "2.0.0",
      "_model_name": "LayoutModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "LayoutView",
      "align_content": null,
      "align_items": null,
      "align_self": null,
      "border_bottom": null,
      "border_left": null,
      "border_right": null,
      "border_top": null,
      "bottom": null,
      "display": null,
      "flex": null,
      "flex_flow": null,
      "grid_area": null,
      "grid_auto_columns": null,
      "grid_auto_flow": null,
      "grid_auto_rows": null,
      "grid_column": null,
      "grid_gap": null,
      "grid_row": null,
      "grid_template_areas": null,
      "grid_template_columns": null,
      "grid_template_rows": null,
      "height": null,
      "justify_content": null,
      "justify_items": null,
      "left": null,
      "margin": null,
      "max_height": null,
      "max_width": null,
      "min_height": null,
      "min_width": null,
      "object_fit": null,
      "object_position": null,
      "order": null,
      "overflow": null,
      "padding": null,
      "right": null,
      "top": null,
      "visibility": null,
      "width": null
     }
    },
    "d14781bec20f41f0baeae04f5808221f": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "HTMLView",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_8491bceba2434248aa96dd9163bada0e",
      "placeholder": "​",
      "style": "IPY_MODEL_e972b2b7008a42ac97b08f1251ddb259",
      "tabbable": null,
      "tooltip": null,
      "value": "100%"
     }
    },
    "df1635a7d8d345a485e5be157c9b7941": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "background": null,
      "description_width": "",
      "font_size": null,
      "text_color": null
     }
    },
    "e15ffd780be2410cac528b1c1dcef6e7": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "FloatProgressModel",
     "state": {
      "_dom_classes": [],
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "FloatProgressModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/controls",
      "_view_module_version": "2.0.0",
      "_view_name": "ProgressView",
      "bar_style": "success",
      "description": "",
      "description_allow_html": false,
      "layout": "IPY_MODEL_6f2c804fca9645de9f53b4183308d9f9",
      "max": 6462886,
      "min": 0,
      "orientation": "horizontal",
      "style": "IPY_MODEL_a52f65ea28b048b0b756ec631a70f064",
      "tabbable": null,
      "tooltip": null,
      "value": 6462886
     }
    },
    "e972b2b7008a42ac97b08f1251ddb259": {
     "model_module": "@jupyter-widgets/controls",
     "model_module_version": "2.0.0",
     "model_name": "HTMLStyleModel",
     "state": {
      "_model_module": "@jupyter-widgets/controls",
      "_model_module_version": "2.0.0",
      "_model_name": "HTMLStyleModel",
      "_view_count": null,
      "_view_module": "@jupyter-widgets/base",
      "_view_module_version": "2.0.0",
      "_view_name": "StyleView",
      "background": null,
      "description_width": "",
      "font_size": null,
      "text_color": null
     }
    }
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}